<template>
  <div>
    <!-- 顶部导航栏 -->
    <van-nav-bar
      :fixed="true"
      title="登录"
      left-text="返回"
      left-arrow
      :placeholder="true"
      @click-left="$router.go(-1)"
    />
    <!-- 输入框 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="手机号"
        :rules="[{ required: true, messgae: '手机号必填哦' }]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        required
        placeholder="验证码"
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          loading-text="加载中..."
          :loading="isLoading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/login'
import { saveToken } from '@/utils/token'
export default {
  name: 'login',
  data () {
    return {
      mobile: '13812345678', //手机号
      code: '246810', //验证码
      isLoading: false
    }
  },
  methods: {
    async onSubmit (values) {
      this.isLoading = true
      try {
        //发送网络请求
        const res = await userLogin(values.mobile, values.code)
        //登录成功提示
        this.$toast.success('登录成功')
        // //保存token
        saveToken(res.data.data)
        //跳转到首页
        this.$router.push('/home')
      } catch (error) {
        this.$toast.fail('账号或验证码错误')
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less">
.van-nav-bar {
  .van-nav-bar__content {
    background-color: #0098fa;
    .van-nav-bar__left {
      .van-nav-bar__text {
        color: #fff;
      }
      .van-icon {
        color: #fff;
      }
    }
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
